package com.gitee.attendance.service.impl;

import com.gitee.attendance.entity.Task;
import com.gitee.attendance.entity.User;
import com.gitee.attendance.service.MessageQueueServiceI;
import com.gitee.attendance.util.baidu.CurrencyUtil;
import com.gitee.attendance.util.baidu.FaceUtil;
import com.gitee.attendance.util.rides.RedisUtil;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("MessageQueueService")
@Transactional
public class MessageQueueServiceImpl implements MessageQueueServiceI {

    private Logger logger = LoggerFactory.getLogger(MessageQueueServiceImpl.class);

    @Autowired
    private FaceUtil faceUtil;

    @Autowired
    private RedisUtil redis;

    public void attendanceb() throws Exception {
        while (true) {
            try {
                String result = redis.leftPop(Task.REDIS_NMAE);
                if(result != null){
                    JSONObject json = new JSONObject(result);
                    String uuid = json.getString(RedisUtil.UUID);
                    String userCode = json.getJSONObject(User.REDIS_NMAE).getString(User.USERCODE);
                    String userFace = json.getJSONObject(User.REDIS_NMAE).getString(User.USERFACE);
                    logger.info(userCode+"处理完毕");
                    redis.set(RedisUtil.REDIS_KEY_RESULT + uuid, this.faceMatch(userCode, userFace),6000);
                }else{
                    logger.debug("没有数据需要处理...");
                }

                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public String faceMatch(String userCode, String userFace) throws Exception {
        JSONObject faceVerifyRes = faceUtil.faceVerify(userFace);

        Number errorCode = (Number) faceVerifyRes.get(CurrencyUtil.ERROR_CODE);

        if (errorCode.doubleValue() == 0) {
            faceVerifyRes = faceVerifyRes.getJSONObject(CurrencyUtil.RESULT);
            logger.debug(faceVerifyRes.toString());
            Number faceLiveness = (Number) faceVerifyRes.get(CurrencyUtil.FACE_LIVENESS);
            Number frr_1e_2 = (Number) faceVerifyRes.getJSONObject(CurrencyUtil.THRESHOLDS).get(CurrencyUtil.FRR_1E);
            if (faceLiveness.doubleValue() >= frr_1e_2.doubleValue()) {
                Object resultObj = redis.get(User.REDIS_KEY + userCode);
                if (resultObj == null) {
                    return "ERROR:未查询到相关结果 " + User.REDIS_KEY + userCode;
                }
                String result = resultObj.toString();
                logger.debug(result.length()>200?result.substring(0, 200)+"...":result);
                JSONObject faceMatchRes;

                try {
                    faceMatchRes = new JSONObject(result);
                } catch (Exception e) {
                    return "ERROR:查询结果格式异常 " + User.REDIS_KEY + userCode;
                }

                String userName = faceMatchRes.getString(User.USERNAME);
                String base = faceMatchRes.getString(User.USERFACE);

                faceMatchRes = faceUtil.faceMatch(userFace, CurrencyUtil.BASE64, base, CurrencyUtil.BASE64);
                errorCode = (Number) faceMatchRes.get(CurrencyUtil.ERROR_CODE);
                if (errorCode.doubleValue() == 0) {
                    faceMatchRes = faceMatchRes.getJSONObject(CurrencyUtil.RESULT);
                    Number similarityDegree = (Number) faceMatchRes.get(CurrencyUtil.SCORE);
                    if (similarityDegree.doubleValue() >= 85) {
                        return "SUCCESS:认定为同一人 " + userName;
                    } else {
                        return "ERROR:相似度过低，请换人或重传 ";
                    }
                } else {
                    String errorMsg = faceMatchRes.getString(CurrencyUtil.ERROR_MSG);
                    return "ERROR:" + errorMsg;
                }
            } else {
                return "ERROR:照片画质过低，请对准拍摄 ";
            }
        } else {
            String errorMsg = faceVerifyRes.getString(CurrencyUtil.ERROR_MSG);
            return "ERROR:" + errorMsg;
        }
    }

}